package apps.qq.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import apps.qq.utils.CookieUtils;

import com.opensymphony.xwork2.ActionSupport;

import connect_tx_sdk.service.ShareToken;
import connect_tx_sdk.service.UserToken;
import connect_tx_sdk.utils.ConnectUtils;

/**
 * 
 * @创建作者：hiyoucai@126.com
 * @创建时间：2011-6-17 下午04:54:11
 * @文件描述：具体绑定业务动作
 */
@Namespace("/qq")
public class BindAction extends ActionSupport implements ServletRequestAware, ServletResponseAware{
	
	private static final long serialVersionUID = -3528657332607901768L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	String connectSession = "";
	String send_qq_message = null;
	
	@Action("bind")
	public String execute() throws Exception{
		
		//这里可以对connectSession进行验证，是否是合法的请求。
		
		String method = request.getMethod().toLowerCase();
		//取出认证成功后的会话串
		String access_token = CookieUtils.getCookieValue(request, "access_token");
		
		//get请求表示到绑定引导页
		if("get".equals(method)){			
			//到绑定引导页
			Map<String, Object> user = new UserToken().user(access_token);
			//读取用户的信息
			request.setAttribute("user", user);			
			return SUCCESS;
		}else{
			//Post请求，绑定引导页提交的绑定请求，这里假设写cookie表示绑定业务了。			
			
			//腾讯要求向QQ空间发送消息的时候，要做到透明，让用户知道自己的动作
			if(send_qq_message != null && "1".equals(send_qq_message)){				
				Map<String, String> params = new HashMap<String, String>();
				params.put("images", "http://mat1.gtimg.com/www/iskin960/qqcomlogo.png");
				params.put("title", "腾讯登录连接测试");
				params.put("url", "http://connect.opensns.qq.com/?t=" + Math.random());
				String html = new ShareToken().share(access_token, params);				
				System.out.println(html);				
			}
			
			//绑定成功后，发一条动态消息到QQ空间，这个接口调用一定要控制时间间隔，小心被腾讯cut掉
			CookieUtils.setCookie(request, response, "is_bind_qq", "1", 7 * 24 * 60 * 60, "/");	
			
			
			//绑定成功页
			String redirect_url = "/qq/welcome.x";
			response.sendRedirect(redirect_url);
			return null;
		}		
		
	}
	
	
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}


	public String getConnectSession() {
		return connectSession;
	}


	public void setConnectSession(String connectSession) {
		this.connectSession = connectSession;
	}


	public String getSend_qq_message() {
		return send_qq_message;
	}


	public void setSend_qq_message(String send_qq_message) {
		this.send_qq_message = send_qq_message;
	}
}
